package com.rc.evcharger.common.mq;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 路由模式
 * MQ消息发送器
 */
@Component
public class CmdMqProducer {
    private static Logger logger = LogManager.getLogger(CmdMqProducer.class);

    @Autowired
    //@Qualifier("cmdAmqpTemplate")
    private AmqpTemplate amqpTemplate;

    /**
     * 直接发送
     * @param queueKey
     * @param object
     */
    public void send(String queueKey, Object object) {
        try {
            amqpTemplate.convertAndSend(queueKey, object);
        } catch (Exception e) {
            logger.error(e);
        }
    }

    /**
     * 延迟发送(毫秒)
     * @param queueKey
     * @param object
     * @param delay    毫秒
     */
    public void sendDelay(String queueKey, Object object, Integer delay) {
        try {
            amqpTemplate.convertAndSend(queueKey, object, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    message.getMessageProperties().setDelay(delay);
                    return message;
                }
            });
        } catch (Exception e) {
            logger.error(e);
        }
    }

    /**
     * 按指定间隔时间发送
     * @param queueKey
     * @param object
     * @param notifyCount 发送计数器
     * @param delay       毫秒
     */
    public void send(String queueKey, Object object, Integer notifyCount, Integer delay) {
        try {
            amqpTemplate.convertAndSend(queueKey, object, new MessagePostProcessor() {

                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    message.getMessageProperties().setDelay(delay);
                    message.getMessageProperties().setHeader("notifyCount", notifyCount);
                    //message.getMessageProperties().setHeader("maxCount", maxCount);
                    //System.out.println(sdf.format(new Date()) + " Delay sent.");
                    return message;
                }
            });
        } catch (Exception e) {
            logger.error(e);
        }
    }
}
